<template>
  <div class="app-container">
    <!-- 新增按钮 -->
    <el-button type="primary" style="margin-bottom: 10px" @click="handleAdd">
      新增
    </el-button>

    <!-- 新增账号弹窗 -->
    <el-dialog
      title="新增账号"
      :visible.sync="addDialogVisible"
      width="400px"
      :close-on-click-modal="false"
    >
      <!-- 新增表单 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
        class="add-form"
      >
        <!-- 用户名输入框 -->
        <el-form-item label="用户名" prop="userAccount">
          <el-input
            v-model="addForm.userAccount"
            placeholder="请输入用户名"
            clearable
          />
        </el-form-item>

        <!-- 密码输入框 -->
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="addForm.password"
            type="password"
            placeholder="请输入密码（至少6位）"
            clearable
          />
        </el-form-item>

        <!-- 确认密码输入框 -->
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="addForm.confirmPassword"
            type="password"
            placeholder="请再次输入密码"
            clearable
          />
        </el-form-item>

        <!-- 角色选择 -->
        <el-form-item label="角色" prop="role">
          <el-select v-model="addForm.role" placeholder="请选择角色" clearable>
            <el-option label="管理员" value="1" />
            <el-option label="普通用户" value="2" />
            <el-option label="访客" value="3" />
          </el-select>
        </el-form-item>
      </el-form>

      <!-- 弹窗底部按钮 -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleAddSubmit">确定新增</el-button>
      </div>
    </el-dialog>

    <!-- 修改账号弹窗 -->
    <el-dialog
      title="修改账号"
      :visible.sync="editDialogVisible"
      width="400px"
      :close-on-click-modal="false"
    >
      <!-- 修改表单 -->
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="100px"
        class="add-form"
      >
        <!-- 用户名输入框 -->
        <el-form-item label="用户名" prop="userAccount">
          <el-input
            v-model="editForm.userAccount"
            placeholder="请输入用户名"
            clearable
          />
        </el-form-item>

        <!-- 密码输入框（修改时可选填） -->
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="editForm.password"
            type="password"
            placeholder="不修改请留空（至少6位）"
            clearable
          />
        </el-form-item>

        <!-- 确认密码输入框 -->
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="editForm.confirmPassword"
            type="password"
            placeholder="请再次输入密码"
            clearable
          />
        </el-form-item>

        <!-- 角色选择 -->
        <el-form-item label="角色" prop="role">
          <el-select v-model="editForm.role" placeholder="请选择角色" clearable>
            <el-option label="管理员" value="1" />
            <el-option label="普通用户" value="2" />
            <el-option label="访客" value="3" />
          </el-select>
        </el-form-item>
      </el-form>

      <!-- 弹窗底部按钮 -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleEditSubmit">确定修改</el-button>
      </div>
    </el-dialog>

    <!-- 账号表格 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column align="center" label="序号" width="95">
        <template slot-scope="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>

      <el-table-column
        label="账号ID"
        width="110"
        align="center"
        :show-overflow-tooltip="true"
        v-if="false"
      >
        <template slot-scope="scope">
          {{ scope.row.user_id }}
        </template>
      </el-table-column>

      <el-table-column label="账号名称" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.user_account }}</span>
        </template>
      </el-table-column>

      <el-table-column label="角色信息" width="110" align="center">
        <template slot-scope="scope">
          {{ formatRole(scope.row.role) }}
        </template>
      </el-table-column>

      <el-table-column
        align="center"
        prop="created_at"
        label="添加时间"
        width="200"
      >
        <template slot-scope="scope">
          <i class="el-icon-time" />
          <span>{{ scope.row.add_time }}</span>
        </template>
      </el-table-column>

      <el-table-column
        class-name="operation-col"
        label="操作"
        width="200"
        align="center"
      >
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="handleEdit(scope.row)">
            修改
          </el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.row)"
            style="margin-left: 5px"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import { getList, addAccount, delAccount, updateAccount } from "@/api/table";

export default {
  data() {
    // 确认密码校验规则（对比密码与确认密码是否一致）
    const validateConfirmPassword = (rule, value, callback) => {
      // 根据当前激活的表单判断使用哪个表单的数据
      const form = this.addDialogVisible ? this.addForm : this.editForm;
      // 当编辑表单且密码为空时，直接通过验证
      if (this.editDialogVisible && !form.password) {
        callback();
      } else if (value !== form.password) {
        callback(new Error("两次输入的密码不一致，请重新输入"));
      } else {
        callback();
      }
    };

    // 修改表单的密码校验（可以为空，不为空则验证长度）
    const validateEditPassword = (rule, value, callback) => {
      if (value && (value.length < 6 || value.length > 32)) {
        callback(new Error("密码长度需在6-32个字符之间"));
      } else {
        callback();
      }
    };

    return {
      list: null,
      listLoading: true,
      // 新增弹窗控制
      addDialogVisible: false,
      // 新增表单数据
      addForm: {
        userAccount: "",
        password: "",
        confirmPassword: "",
        role: "2",
      },
      // 新增表单验证规则
      addFormRules: {
        userAccount: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 2,
            max: 20,
            message: "用户名长度需在2-20个字符之间",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 32,
            message: "密码长度需在6-32个字符之间",
            trigger: "blur",
          },
        ],
        confirmPassword: [
          { required: true, message: "请再次输入密码", trigger: "blur" },
          { validator: validateConfirmPassword, trigger: "blur" },
        ],
        role: [{ required: true, message: "请选择角色", trigger: "change" }],
      },
      // 修改弹窗控制
      editDialogVisible: false,
      // 修改表单数据
      editForm: {
        userId: "", // 用于存储当前编辑的用户ID
        userAccount: "",
        password: "",
        confirmPassword: "",
        role: "2",
      },
      // 修改表单验证规则（密码可选填）
      editFormRules: {
        userAccount: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 2,
            max: 20,
            message: "用户名长度需在2-20个字符之间",
            trigger: "blur",
          },
        ],
        password: [{ validator: validateEditPassword, trigger: "blur" }],
        confirmPassword: [
          {
            validator: (rule, value, callback) => {
              // 仅当密码有值时才验证
              if (!this.editForm.password) {
                callback(); // 密码为空时不校验确认密码
                return;
              }
              // 密码不为空时，确认密码必填且需一致
              if (!value) {
                callback(new Error("请再次输入密码"));
              } else if (value !== this.editForm.password) {
                callback(new Error("两次输入的密码不一致，请重新输入"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        role: [{ required: true, message: "请选择角色", trigger: "change" }],
      },
    };
  },
  created() {
    this.fetchData();
  },
  methods: {
    // 获取表格数据
    fetchData() {
      this.listLoading = true;
      getList()
        .then((response) => {
          this.list = response.data;
          this.listLoading = false;
        })
        .catch(() => {
          this.listLoading = false;
          this.$message.error("数据加载失败，请重试");
        });
    },

    formatRole(roleValue) {
      const roleMap = {
        1: "管理员",
        2: "普通用户",
        3: "访客",
      };
      return roleMap[roleValue] || "未知角色";
    },

    // 打开新增弹窗
    handleAdd() {
      this.$nextTick(() => {
        this.$refs.addFormRef.resetFields();
      });
      this.addDialogVisible = true;
    },

    // 提交新增表单
    handleAddSubmit() {
      this.$refs.addFormRef.validate((isValid) => {
        if (isValid) {
          const addParams = {
            user_account: this.addForm.userAccount,
            password: this.addForm.password,
            role: this.addForm.role,
          };

          addAccount(addParams)
            .then(() => {
              this.$message.success("账号新增成功");
              this.addDialogVisible = false;
              this.fetchData();
            })
            .catch(() => {
              this.$message.error("账号新增失败，请重试");
            });
        } else {
          return false;
        }
      });
    },

    // 打开修改弹窗
    handleEdit(row) {
      // 重置表单
      this.$nextTick(() => {
        this.$refs.editFormRef.resetFields();
      });
      // 回显数据
      this.editForm = {
        userId: row.user_id,
        userAccount: row.user_account,
        password: "",
        confirmPassword: "",
        role: row.role + "", // 确保类型一致
      };
      // 显示弹窗
      this.editDialogVisible = true;
    },

    // 提交修改表单
    handleEditSubmit() {
      this.$refs.editFormRef.validate((isValid) => {
        if (isValid) {
          // 构造修改参数
          const editParams = {
            user_id: this.editForm.userId,
            user_account: this.editForm.userAccount,
            role: this.editForm.role,
          };
          // 只有输入了密码才传递密码参数
          if (this.editForm.password) {
            editParams.password = this.editForm.password;
          }

          // 调用修改接口
          updateAccount(editParams)
            .then(() => {
              this.$message.success("账号修改成功");
              this.editDialogVisible = false;
              this.fetchData();
            })
            .catch(() => {
              this.$message.error("账号修改失败，请重试");
            });
        } else {
          return false;
        }
      });
    },

    // 删除操作
    handleDelete(row) {
      this.$confirm("确定要删除该账号吗？", "删除确认", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delAccount(row.user_id)
            .then(() => {
              this.$message.success("账号删除成功");
              this.fetchData();
            })
            .catch(() => {
              this.$message.error("删除失败");
            });
        })
        .catch(() => {
          this.$message({ type: "info", message: "已取消删除" });
        });
    },
  },
};
</script>

<style scoped>
.add-form {
  margin-top: 15px;
}
.dialog-footer {
  text-align: right;
}
</style>
